<template>
  <div class="app-container bg-white">
    <div class="page-body">
      <el-row>
        <el-col :span="8">
          <el-button size="mini" type="success" icon="el-icon-document-add" @click="addOption()" v-if="roleBtns.includes('sys:category:save') || $store.getters.isAdmin">新建分类</el-button>
          <br><br>
          <div class="tree_box" v-loading="loading">
            <el-tree :data="pageData" :expand-on-click-node="false" @node-click="showOption" :props="{ children: 'goodsCategoryModelList', label: 'title' }" node-key="index" highlight-current>
              <span class="custom-tree-node" slot-scope="{ node, data }">
                <span>{{ node.label }}</span>
                <span class="custom-tree-node-tools">
                  <el-button type="text" size="mini" @click.stop="addOption(data)" v-if="(roleBtns.includes('sys:category:save') || $store.getters.isAdmin) && data.level < 3">新增子级</el-button>
                  <el-button type="text" size="mini" @click.stop="editOption(data)" v-if="roleBtns.includes('sys:category:update') || $store.getters.isAdmin">编辑</el-button>
                  <!-- <el-button type="text" size="mini" @click.stop="editOption(data)" v-if="roleBtns.includes('sys:fincial:update') || $store.getters.isAdmin">编辑</el-button> -->
                  <el-button type="text" size="mini" @click.stop="removeOption(data.id)" v-if="roleBtns.includes('sys:category:remove') || $store.getters.isAdmin">删除</el-button>
                </span>
              </span>
            </el-tree>
          </div>
        </el-col>
        <el-col :span="16">
          <div class="title font-size--md font-weight--lg">{{title}}分类</div>
          <app-class-form ref="editClassFormRef" :mode="isEditorMode" :classList="pageData" @submit="submitForm()" @submitFincial="submitFincialForm"></app-class-form>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
import Setting from '@/settings';
import { mapGetters } from 'vuex';
import AppClassForm from '../components/classForm.vue';
import { GetStoreClassList, GetStoreClassDetail, SaveStoreClass, EditStoreClass, RemoveStoreClass,BindFincialCategory } from '@/views/store-management/services/index';
export default {
  name: 'StoreClass',
  components: {
    AppClassForm
  },
  computed: {
    ...mapGetters(['roleBtns']),
    title() {
      return this.isShowerMode ? '查看' : (this.isEditorMode ? '编辑' : '新建');
    }
  },
  data() {
    return {
      pageData: [],
      defaultPageData: [],
      loading: false,
      isEditorMode: false,
      isShowerMode: false,
      editorNodeId: ''
    }
  },
  methods: {
    submitForm() {
      if (!this.validClassForm()) return;
      if (this.isEditorMode) {
        EditStoreClass({
          id: this.editorNodeId,
          ...this.formatClassForm()
        })
        .then(data => {
          if (data.code == 200) {
            this.$message.success('修改成功!');
            this.$refs.editClassFormRef.resetClassForm();
            this.$refs.editClassFormRef.changeNodeLength();
            this.getPageDataList();
            this.isEditorMode = false;
            this.isShowerMode = false;
            this.$refs.editClassFormRef.disabled = false;
          } else {
            this.$message.error('修改失败!');
          }
        })
      } else {
        if(this.formatClassForm().categoryNo) {
        SaveStoreClass(this.formatClassForm())
        .then(data => {
          if (data.code == 200) {
            this.$message.success('新建成功!');
            this.$refs.editClassFormRef.resetClassForm();
            this.$refs.editClassFormRef.changeNodeLength();
            this.getPageDataList();
            this.isEditorMode = false;
            this.isShowerMode = false;
            this.$refs.editClassFormRef.disabled = false;
          } else {
            this.$message.error('新建失败!');
          }
        })
        }else {
          this.$message.warning('请填写分类编码！')
        }
      }
    },
    submitFincialForm(data) {
       console.log(data)
       if(data && data.length>0) {
         let targetIds = data.map(item => {
           return item.id
         })
         BindFincialCategory({
           id: this.editorNodeId,
           targetIds: targetIds.join(",")
         }).then(res => {
           if(res.code == 200) {
              this.$message.success('绑定成功！')
              this.$refs.editClassFormRef.resetClassForm();
              this.$refs.editClassFormRef.changeNodeLength();
              this.getPageRateDataList();
              this.isEditorMode = false;
              this.isShowerMode = false;
              this.$refs.editClassFormRef.disabled = true;
              this.$refs.editClassFormRef.fincialdisabled = false;
           }else {
             this.$message.error('绑定失败！')
           }
         })
       }
    },
    // 新增功能
    addOption(node) {
      // 清空数据
      this.isShowerMode = false;
      this.isEditorMode = false;
      this.$refs.editClassFormRef.disabled = false;
      this.$refs.editClassFormRef.isShowParentNode = true;
      this.$refs.editClassFormRef.resetClassForm();
      this.$refs.editClassFormRef.changeNodeLength();
      // 是否为新增子级
      if (!node) return;
      if (node.parentId != '0') {
        this.$refs.editClassFormRef.classForm.parentNode = [node.parentId, node.id];
        this.$refs.editClassFormRef.classForm.tags = [null,null,null,null];
        this.$refs.editClassFormRef.changeNodeLength();
      } else {
        this.$refs.editClassFormRef.classForm.parentNode = [node.id];
        this.$refs.editClassFormRef.classForm.tags = [null,null,null,null];
        this.$refs.editClassFormRef.changeNodeLength();
      }
    },
    // 查看详情
    showOption(node) {
      this.isEditorMode = false;
      this.isShowerMode = true;
      this.$refs.editClassFormRef.disabled = true;
      this.editorNodeId = node.id;
      switch (node.level) {
        case 1:
          this.$refs.editClassFormRef.isShowParentNode = false;
          this.$refs.editClassFormRef.classForm.parentNode = [];
          break;
        case 2:
          this.$refs.editClassFormRef.isShowParentNode = true;
          this.$refs.editClassFormRef.classForm.parentNode = [node.parentId];
          break;
        case 3:
          this.$refs.editClassFormRef.isShowParentNode = true;
          this.$refs.editClassFormRef.classForm.parentNode = this.findParentNodeId(node.parentId, this.pageData);
          break;
      }
      this.$refs.editClassFormRef.finailForm.classId = this.editorNodeId;
      GetStoreClassDetail({
        id: node.id
      })
      .then(data => {
        if (data.code == 200) {
          this.$refs.editClassFormRef.classForm.title = data.data.title;
          this.$refs.editClassFormRef.classForm.number = data.data.categoryNo;
          this.$refs.editClassFormRef.classForm.sort = data.data.sort;
          this.$refs.editClassFormRef.classForm.imgUrl = data.data.imgUrl;
          this.$refs.editClassFormRef.classForm.level = data.data.level;
          this.$refs.editClassFormRef.classForm.status = data.data.status;
          this.$refs.editClassFormRef.classForm.sizeTemplateId = data.data.sizeTemplateId;
          this.$refs.editClassFormRef.classForm.tags = Array.from({length: 4}, (val, index) => {
            const finder = data.data.categoryPropertyList.find(item => item.sort == index + 1);
            return finder || null;
          });
        } else {
          this.$message.error('分类详情获取失败!');
        }
      })
    },
    sortKey(array, key) {
    return array.sort(function(a, b) {
      var x = a[key];
      var y = b[key];
      return x < y ? -1 : x > y ? 1 : 0;
    });
    },
    // 编辑功能
    editOption(node) {
      this.isShowerMode = false;
      this.isEditorMode = true;
      if(this.roleBtns.includes('sys:category:update') || this.$store.getters.isAdmin) {
      this.$refs.editClassFormRef.disabled = false;
      this.$refs.editClassFormRef.fincialdisabled = true;
      }else {
        this.$refs.editClassFormRef.disabled = true;
        this.$refs.editClassFormRef.fincialdisabled = false;
      }
      this.editorNodeId = node.id;
      switch (node.level) {
        case 1:
          this.$refs.editClassFormRef.isShowParentNode = false;
          this.$refs.editClassFormRef.classForm.parentNode = [];
          break;
        case 2:
          this.$refs.editClassFormRef.isShowParentNode = true;
          this.$refs.editClassFormRef.classForm.parentNode = [node.parentId];
          break;
        case 3:
          this.$refs.editClassFormRef.isShowParentNode = true;
          this.$refs.editClassFormRef.classForm.parentNode = this.findParentNodeId(node.parentId, this.pageData);
          break;
      }
      GetStoreClassDetail({
        id: node.id
      })
      .then(data => {
        if (data.code == 200) {
          this.$refs.editClassFormRef.classForm.title = data.data.title;
          this.$refs.editClassFormRef.classForm.number = data.data.categoryNo;
          this.$refs.editClassFormRef.classForm.sort = data.data.sort;
          this.$refs.editClassFormRef.classForm.imgUrl = data.data.imgUrl;
          this.$refs.editClassFormRef.classForm.level = data.data.level;
          this.$refs.editClassFormRef.classForm.status = data.data.status;
          this.$refs.editClassFormRef.classForm.sizeTemplateId = data.data.sizeTemplateId;
          this.$refs.editClassFormRef.classForm.tags = Array.from({length: 4}, (val, index) => {
            const finder = data.data.categoryPropertyList.find(item => item.sort == index + 1);
            return finder || null;
          });
        } else {
          this.$message.error('分类详情获取失败!');
        }
      })
    },
    // 删除功能
    removeOption(nodeId) {
      this.$confirm('此操作将删除该分类, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true;
            instance.confirmButtonText = '加载中...';
            RemoveStoreClass({ id: nodeId })
            .then(data => {
              instance.confirmButtonLoading = false;
              if (data.code == 200) {
                const childIds = this.findChildIdsById(nodeId, this.defaultPageData);
                if (childIds.includes(this.editorNodeId)) {
                  this.addOption();
                }
                done();
                this.$message.success('删除成功!');
                this.getPageDataList();
              } else {
                this.$message.error('删除失败!');
              }
            })
            .catch(error => {
              instance.confirmButtonLoading = false;
            })
          } else {
            done();
          }
        }
      })
    },
    // 获取树形结构的全部数据
    getPageDataList() {
      this.loading = true;
      GetStoreClassList()
      .then(data => {
        if (data.code == 200) {
          this.defaultPageData = data.data;
          this.pageData = JSON.parse(JSON.stringify(data.data));
        } else {
          this.$message.error('数据获取失败!');
        }
        this.loading = false;
      })
      .catch(() => {
        this.loading = false;
      })
    },
    validClassForm() {
      const classForm = this.$refs.editClassFormRef.classForm;
      if (!classForm.title) {
        this.$message.warning('请输入分类名称!');
        return;
      }
      if (!classForm.number) {
        this.$message.warning('请输入分类编码!');
        return;
      }
      if (!(Setting.expression[0].value).test(classForm.number)) {
        this.$message.warning('分类编码只能输入字母和数字!');
        return false;
      }
      if (!classForm.sort) {
        this.$message.warning('请输入排序!');
        return false;
      }
      // if (!(/^[0-9]+$/).test(classForm.sort)) {
      //   this.$message.warning('排序只能输入数字!');
      //   return false;
      // }
      return true;
    },
    // 整合数据
    formatClassForm() {
      const classForm = this.$refs.editClassFormRef.classForm;
      let rules = '';
      if (classForm.parentNode && classForm.parentNode.length) {
        const firstNode = this.pageData.find(item => item.id == classForm.parentNode[0]);
        rules = firstNode.title;

        if (classForm.parentNode[1]) {
          const secondNode = firstNode.goodsCategoryModelList.find(item => item.id == classForm.parentNode[1]);
          rules = rules + '-' + secondNode.title + '-' + classForm.title;
        } else {
          rules = rules + '-' + classForm.title;
        }
      } else {
        rules = classForm.title;
      }
      return {
        parentId: (classForm.parentNode && classForm.parentNode.length) ? classForm.parentNode[classForm.parentNode.length -1] : '0',
        title: classForm.title,
        categoryNo: classForm.number,
        sort: Number(classForm.sort),
        imgUrl: classForm.imgUrl,
        level: (classForm.parentNode && classForm.parentNode.length) ? classForm.parentNode.length + 1 : 1, // 1一级 2二级 3三级
        categoryPropertyList: classForm.tags.filter(item => item),
        creatorId: JSON.parse(this.$store.getters.userInfo).id ? JSON.parse(this.$store.getters.userInfo).id : '1',
        status: 1,
        sizeTemplateId: classForm.sizeTemplateId?classForm.sizeTemplateId:null,
        relationRule: rules
      }
    },
    findParentNodeId(id, dataList) {
      var idsList = [];
      var forFunction = (list, id) => {
        for (var i = 0; i < list.length; i++) {
          var item = list[i];
          if (item.id == id) {
            idsList.unshift(item.id);
            forFunction(dataList, item.parentId);
            break;
          } else {
            if (item.goodsCategoryModelList) {
              forFunction(item.goodsCategoryModelList, id);
            }
          }
        }
      }
      forFunction(dataList, id);
      return idsList;
    },
    findChildIdsById(id, dataList) {
      var idsList = [];
      var forFunction = (list, id) => {
        for (var i = 0; i < list.length; i++) {
          var item = list[i];
          if (item.id == id) {
            pushChild(item);
            break;
          } else {
            if (item.goodsCategoryModelList) {
              forFunction(item.goodsCategoryModelList, id);
            }
          }
        }
      }
      var pushChild = (data) => {
        idsList.push(data.id);
        if (data.goodsCategoryModelList && data.goodsCategoryModelList.length) {
          data.goodsCategoryModelList.forEach(dataItem => {
            pushChild(dataItem);
          })
        }
      }
      forFunction(dataList, id);
      return idsList;
    }
  },
  created() {
    this.getPageDataList();
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-tree-node__content {
  height: 38px;
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;

  .custom-tree-node-tools {
    opacity: 0;
    transition: opacity 0.1s ease-in-out;
  }

  &:hover {

    .custom-tree-node-tools {
      opacity: 1;
    }
  }
}

.title {
  padding-left: 140px;
}

.tree_box {
  max-height: 635px;
  overflow-y: auto;
}
</style>
